
import requests as req;
import os;
import time;
from Crypto.Cipher import AES
from binascii import b2a_hex, a2b_hex
# 导包 线程池
from multiprocessing.dummy import Pool;

def get_list(url,params):

    proxy = '175.146.208.34:9999'  # 本地代理
    proxies = {
        'http': 'http://' + proxy,
        'https': 'https://' + proxy
    }

    # UA伪装
    header = {
        "User-Agent":"User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36 MicroMessenger/7.0.9.501 NetType/WIFI MiniProgramEnv/Windows WindowsWechat",
        "Mobile-User-Agent":"Mozilla/5.0 (Linux; Android 5.0; SM-G900P Build/LRX21T) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Mobile Safari/537.36"
    }
    # 文件夹路径
    dir_path = "./bug_file/" + params.get("name");

    # 获取 M3U8
    m3u8 = req.get(url, proxies=proxies, headers=header).text;
    if len(m3u8) > 0:

        # 把url写到文本
        text_file_name = params.get("name") + "_urls.txt";
        with open(dir_path + "/" + text_file_name, "a+", encoding="utf-8") as wf:
            for item in m3u8:
                wf.write(str(item));

        # 地址解析
        ts_urls = [];
        with open(dir_path + "/" + text_file_name, "r", encoding="utf-8") as rf:
            lines = rf.readlines();
            for line in lines:
                start = line.find("https://");
                if ("#EXT-X-KEY" in line):
                    ts_urls.append(line[start:-1].strip());
                elif (start != -2):
                    ts_urls.append(line[start:].strip());
                else:
                    continue;

        # 创建线程池
        # pool = Pool(5);

        # 获取 ts
        key = "";  # key
        stor = [];  # 顺序

        for index, item in enumerate(ts_urls):

            if (index == 0):
                key = req.get(item, proxies=proxies).text;
                print(key)
            else:

                result = req.get(item, proxies=proxies, headers=header);
                io = result.content;

                file_name = str(index) + ".ts";
                stor.append(file_name);
                with open(dir_path + "/" + file_name, "wb") as wf:
                    wf.write(io);

                print(f"剩余{len(ts_urls) - index}未下载...");

        # ts合并生成 mp4
        tsToMp4(dir_path);

    else:
        print("爬取失败!!");


    # return len(json);


# 加密函数
def encrypt(text):
    key = '9999999999999999'.encode('utf-8')
    mode = AES.MODE_ECB
    text = add_to_16(text)
    cryptos = AES.new(key, mode)

    cipher_text = cryptos.encrypt(text)
    return b2a_hex(cipher_text)


# 解密后，去掉补足的空格用strip() 去掉
def decrypt(text):
    key = '6bf0a290effdcdc9'.encode('utf-8')
    mode = AES.MODE_ECB
    cryptor = AES.new(key, mode)
    plain_text = cryptor.decrypt(a2b_hex(text))
    return bytes.decode(plain_text).rstrip('\0')

# 整合所有ts文件，保存为mp4格式
def tsToMp4(dir):
    print("开始合并...")
    root = dir
    outdir = "output"
    os.chdir(root)
    if not os.path.exists(outdir):
        os.mkdir(outdir)
    os.system("copy /b *.ts new.mp4")
    os.system("move new.mp4 {}".format(outdir))
    print("结束合并...")


if __name__ == '__main__':

    # name = input("请输入您要看的影片名:\n");

    name = "你好,李焕英";
    if(not os.path.exists("bug_file/"+name)):
        os.mkdir("bug_file/"+name);

    url = "https://video.hcyunshang.cn/20210215/cEkErZnB/1000kb/hls/index.m3u8";

    # print("================================ 数据爬取中 ================================ \r");

    # for index in range(0,1000):
    #     params = {
    #         "type": int(type),
    #         "interval_id": "100:90",  # 好评比率,好于100%-90%的喜剧片
    #         "action": "",
    #         "start": index * 20,
    #         "limit": 20
    #     };
    params = {
        "name":name
    };


    # num = get_list(url,params);

        # if num > 0:
        #     continue;
        # else:
        #     break;

    # tsToMp4("bug_file/"+name)

    with open("bug_file/你好,李焕英/1.ts","rb") as rf:
        lines = rf.readlines();
        text = "";
        for line in lines:
            text += str(line);

        temp = decrypt(text);

        text_file_name = "bug_file/你好,李焕英/999999.ts";
        with open(text_file_name, "a+", encoding="utf-8") as wf:
                wf.write(str(temp));




# 如果text不足16位的倍数就用空格补足为16位
def add_to_16(text):
    if len(text.encode('utf-8')) % 16:
        add = 16 - (len(text.encode('utf-8')) % 16)
    else:
        add = 0
    text = text + ('\0' * add)
    return text.encode('utf-8')